<?php

if(!defined('IN_UCHOME')) {
	exit('Access Denied');
}

$eventid = isset($_GET['id']) ? intval($_GET['id']) : 0;
$op = empty($_GET['op']) ? "edit" : $_GET['op'];

$menus = array();
$menus[$op] = " class='active'";

// 获取活动分类信息
if(!@include_once(S_ROOT.'./data/data_eventclass.php')) {
	include_once(S_ROOT.'./source/function_cache.php');
	eventclass_cache();
}

// 发布/编辑
if(submitcheck('infosubmit')) {
	

	//验证码
	if(checkperm('seccode') && !ckseccode($_POST['seccode'])) {
		showmessage('incorrect_code');
	}
	
	$ship_pic = upload_image($_FILES['image'],'_pic');
	$shipflag = upload_image($_FILES['shipflag']);
	
	// 基本信息
	$arr = array(
		"title" => getstr($_POST['title'], 80, 1, 1, 1),
		"deal" => getstr($_POST['deal'], 20, 1, 1, 1),
		"ship_name"	=> getstr($_POST['ship_name'],20,1,1),
		"ship_type"	=> getstr($_POST['ship_type'],20,1,1),
		"capacity"	=> intval($_POST['capacity']),
		"value"	=> getstr($_POST['value'],20,1,1),
		"ship_year"	=> $_POST['ship_year'],
		"shipflag"	=> $shipflag,
		"society"	=> getstr($_POST['society'],80,1,1),
		"image" => $ship_pic,
		"company" => getstr($_POST['company'],80,1,1),
		"linkman" => getstr($_POST['linkman'],20,1,1),
		"phone" => getstr($_POST['phone'],20,1,1),
		"fax" => getstr($_POST['fax'],20,1,1),
		"email" => getstr($_POST['email'],80,1,1),
		"content" => $_POST['content'],
		"dateline" => time()
		
	);
	
	//检查输入
	if(empty($arr['title'])){
		showmessage('title_empty');
	}elseif(empty($arr['ship_name'])){
		showmessage('name_empty');
	} elseif(empty($arr['company'])){
		showmessage('company_empty');
	} elseif(empty($arr['linkman'])) {
		showmessage('linkman_empty');
	}  
	
	if($eventid){// 修改已有活动
			updatetable("buyship", $arr, array("id"=>$eventid));	
			showmessage('do_success', 'space.php?do=buyship&id='.$eventid, 0);			
	} else {// 生成新的活动
	
		//实名认证
		ckrealname('buyship');
		
		//视频认证
		ckvideophoto('buyship');
		
		//新用户见习
		cknewuser();
	
		$_POST['bnid'] = topic_check($_POST['bnid'], 'buyship');
		$arr['id'] = $_POST['bnid'];
		
		// 创建者
		$arr['uid'] = $_SGLOBAL['supe_uid'];
		$arr['username'] = $_SGLOBAL['supe_username'];
	
	
		// 插入 活动（cargo） 表
		$buyshipid = inserttable("buyship", $arr, 1);
		if (!$buyshipid){
			showmessage("event_create_failed"); // 创建活动失败，请检查你输入的内容
		}

		include_once(S_ROOT.'./source/function_feed.php');
		feed_publish($buyshipid, 'buyshipid', 1);
		
		$url = 'space.php?do=buyship';
	
		showmessage('do_success', $url, 0); // 查看活动
	}
}

if('delete'==$op) {
	// 删除/取消 活动

	if(! $eventid){
		showmessage("event_does_not_exist"); // 活动不存在或者已被删除
	}

	if(submitcheck("deletesubmit")){
		include_once(S_ROOT.'./source/function_delete.php');
		deletebuyship(array($eventid));
		showmessage("do_success", "space.php?do=buyship", 2);
	}	

}elseif($op == 'edit'){// 创建、编辑一个新活动
	
	if($eventid) {
		$sql = "select * from ".tname('buyship')." WHERE id = ".$eventid;
		$query = $_SGLOBAL['db']->query($sql);
		while ($value = $_SGLOBAL['db']->fetch_array($query)) {
			$cargo = $value;
		}
		//print_R($cargo);
	} else {
		//检查用户所在组发活动权限
		if(! checkperm("allowevent")){
		   showmessage('no_privilege_add_event');
		}
		
		//实名认证
		ckrealname('event');
		
		//视频认证
		ckvideophoto('event');
		
		//新用户见习
		cknewuser();
		
		//参与热点
		$topic = array();
		$topicid = $_GET['topicid'] = intval($_GET['topicid']);
		if($topicid) {
			$topic = topic_get($topicid);
		}
		if($topic) {
			$actives = array('event' => ' class="active"');
		}
	}
	
	//关联群组
	$mtags = array();
	if(!$eventid || $event['uid']==$_SGLOBAL['supe_uid']) {
		$query = $_SGLOBAL['db']->query("SELECT mtag.* FROM ".tname("tagspace")." st LEFT JOIN ".tname("mtag")." mtag ON st.tagid=mtag.tagid WHERE st.uid='$_SGLOBAL[supe_uid]' AND st.grade=9");
		while($value=$_SGLOBAL['db']->fetch_array($query)) {
			$mtags[] = $value;
		}
	}
	
	if($_GET['tagid'] && !$event['tagid']) {
		$event['tagid'] = intval($_GET['tagid']);		
	}
	
}

realname_get();

include template("cp_buyship");


// 审核活动成员、设置、取消活动组织者
// [to do: 可加入黑名单功能，只需改status为-2，在进入活动时检查即可。优先级：低]
function verify_eventmembers($uids, $status){
	global $_SGLOBAL, $event;	

	if($_SGLOBAL['supe_userevent']['status'] < 3){
		showmessage('no_privilege_manage_event_members');
	}
	$eventid = $_SGLOBAL['supe_userevent']['eventid'];
	if($eventid != $event['eventid']){
		$query = $_SGLOBAL['db']->query("SELECT * FROM ".tname("event")." WHERE eventid='$eventid'");
		$event = $_SGLOBAL['db']->fetch_array($query);
	}
	
	$status = intval($status);
	if($status < -1 || $status > 3){
		showmessage("bad_userevent_status"); // 请选择正确的活动成员状态
	}
	if($event['verify'] == 0 && $status == 0){
		showmessage("event_not_set_verify");
	}
	if($status == 3 && $_SGLOBAL['supe_uid'] != $event['uid']){
		showmessage("only_creator_can_set_admin"); // 只有创建者可以设管理员
	}
	
	$newids = $actions = $userevents = array();
	$num = 0; // 活动人数变化
	$query = $_SGLOBAL['db']->query("SELECT ue.*, sf.* FROM " . tname("userevent") . " ue LEFT JOIN ".tname("spacefield")." sf ON ue.uid=sf.uid WHERE ue.uid IN (".simplode($uids).") AND ue.eventid='$eventid'");
	while($value = $_SGLOBAL['db']->fetch_array($query)){
		if($value['status'] == $status || $event['uid'] == $value['uid'] || $value['status'] == 1){
			// 相同 status 者，创建者，关注者 不处理
			continue;
		}
		if($status == 2) {//设为普通成员
			$newids[] = $value['uid'];
			$userevents[$value['uid']] = $value;
			if($value['status'] == 0){// 加入
				$actions[$value['uid']] = "set_verify";
				$num += ($value['fellow'] + 1);
			} elseif ($value['status'] == 3) { // 取消组织者身份
				$actions[$value['uid']] = "unset_admin";
			}
		} elseif($status == 3) {//设为组织者
			$newids[] = $value['uid'];
			$userevents[$value['uid']] = $value;
			$actions[$value['uid']] = "set_admin";
			if($value['status'] == 0){
				$num += ($value['fellow'] + 1);
			}
		} elseif($status == 0) {//设为待审核
			$newids[] = $value['uid'];
			$userevents[$value['uid']] = $value;
			$actions[$value['uid']] = "unset_verify";
			if($value['status'] >= 2){
				$num -= ($value['fellow'] + 1);
			}
		} elseif($status == -1) {//删除成员
			$newids[] = $value['uid'];
			$userevents[$value['uid']] = $value;
			$actions[$value['uid']] = "set_delete";
			if($value['status'] >= 2){
				$num -= ($value['fellow'] + 1);
			}
		}
	}
	
	if(empty($newids)) return array();
	if($event['limitnum'] > 0 && $event['membernum'] + $num > $event['limitnum']){
		// 活动人数超了
		showmessage("event_will_full");
	}
	
	$note_inserts = $note_ids = $feed_inserts = array();
	$feedarr = array(
		'appid' => UC_APPID,
		'icon' => 'event',
		'uid' => '',
		'username' => '',
		'dateline' => $_SGLOBAL['timestamp'],
		'title_template' => cplang('event_join'), 
		'title_data' => array('title'=>$event['title'], "eventid"=>$event['eventid'], "uid"=>$event['uid'], "username"=>$event['username']),
		'body_template' => '',
		'body_data' => array(),
		'body_general' => '',
		'image_1' => '',
		'image_1_link' => '',
		'image_2' => '',
		'image_2_link' => '',
		'image_3' => '',
		'image_3_link' => '',
		'image_4' => '',
		'image_4_link' => '',
		'target_ids' => '',
		'friend' => ''
	);
	$feedarr = sstripslashes($feedarr);//去掉转义
	$feedarr['title_data'] = serialize(sstripslashes($feedarr['title_data']));//数组转化
	$feedarr['body_data'] = serialize(sstripslashes($feedarr['body_data']));//数组转化
	$feedarr['hash_template'] = md5($feedarr['title_template']."\t".$feedarr['body_template']);//喜好hash
	$feedarr['hash_data'] = md5($feedarr['title_template']."\t".$feedarr['title_data']."\t".$feedarr['body_template']."\t".$feedarr['body_data']);//合并hash
	$feedarr = saddslashes($feedarr);//增加转义

	foreach ($newids as $id){
		if($status > 1 && $userevents[$id]['status'] ==0){
			// 通过审核参加了活动，发布参加活动feed
			$feedarr['uid'] = $userevents[$id]['uid'];
			$feedarr['username'] = $userevents[$id]['username'];
			$feed_inserts[] = "('$feedarr[appid]', 'event', '$feedarr[uid]', '$feedarr[username]', '$feedarr[dateline]', '0', '$feedarr[hash_template]', '$feedarr[hash_data]', '$feedarr[title_template]', '$feedarr[title_data]', '$feedarr[body_template]', '$feedarr[body_data]', '$feedarr[body_general]', '$feedarr[image_1]', '$feedarr[image_1_link]', '$feedarr[image_2]', '$feedarr[image_2_link]', '$feedarr[image_3]', '$feedarr[image_3_link]', '$feedarr[image_4]', '$feedarr[image_4_link]')";
		}
		$userevents[$id]['privacy'] = empty($userevents[$id]['privacy']) ? array() : unserialize($userevents[$id]['privacy']);
		$filter = empty($userevents[$id]['privacy']['filter_note'])?array():array_keys($userevents[$id]['privacy']['filter_note']);
		if(cknote_uid(array("type"=>"eventmemberstatus","authorid"=>$_SGLOBAL['supe_uid']),$filter)){
			$note_ids[] = $id;
			$note_msg = cplang('eventmember_'.$actions[$id], array("space.php?do=event&id=".$event['eventid'], $event['title']));
			$note_inserts[] = "('$id', 'eventmemberstatus', '1', '$_SGLOBAL[supe_uid]', '$_SGLOBAL[supe_username]', '".addslashes($note_msg)."', '$_SGLOBAL[timestamp]')";
		}
	}
	
	if($note_ids) {
		$_SGLOBAL['db']->query("INSERT INTO ".tname('notification')." (`uid`, `type`, `new`, `authorid`, `author`, `note`, `dateline`) VALUES ".implode(',', $note_inserts));
		$_SGLOBAL['db']->query("UPDATE ".tname('space')." SET notenum=notenum+1 WHERE uid IN (".simplode($note_ids).")");
	}
	if($feed_inserts){
		$_SGLOBAL['db']->query("INSERT INTO ".tname('feed')." (`appid` ,`icon` ,`uid` ,`username` ,`dateline` ,`friend` ,`hash_template` ,`hash_data` ,`title_template` ,`title_data` ,`body_template` ,`body_data` ,`body_general` ,`image_1` ,`image_1_link` ,`image_2` ,`image_2_link` ,`image_3` ,`image_3_link` ,`image_4` ,`image_4_link`) VALUES ".implode(',', $feed_inserts));
	}

	if($status == -1){// 删除		
		$_SGLOBAL['db']->query("DELETE FROM ".tname("userevent")." WHERE uid IN (".simplode($newids).") AND eventid='$eventid'");
	} else {// 设置状态		
		$_SGLOBAL['db']->query("UPDATE ".tname("userevent")." SET status='$status' WHERE uid IN (".simplode($newids).") AND eventid='$eventid'");
	}
	// 修改活动人数
	if($num != 0){
		$_SGLOBAL['db']->query("UPDATE ".tname("event")." SET membernum = membernum + ($num) WHERE eventid='$eventid'");
	}
	return $newids;
}


function upload_image($imgpath,$typeid='')
{
	$name=$imgpath["name"];
	$tmp_name=$imgpath["tmp_name"];
	$type=$imgpath["type"];
	$size=$imgpath["size"];
	$hz = strstr($imgpath["name"],'.');
	$uploadfile = './attachment/upload_image/'.date('Ymd',time()).time().$typeid.$hz;

	$maxsize=500*1024;                                           //最大允许上许文件大小
	if($name=="")                                             //文件名为空
	{
		/*showmessage("<script>alert('请先选择要上传的图片文件!'); 
		window.history.back();</script>");*/
		/*echo"<script>alert('upload_img'); 
		window.history.back();</script>";*/
		showmessage('upload_img','javascript:window.history.back();',1);

	}
	if($type!="image/pjpeg" && $type!="image/jpeg" && $type!="image/gif")//文件类型不在指定范围
	{
		/*echo"<script>alert('upload_imgtype');
		window.history.back();</script>";*/
		showmessage('upload_imgtype','javascript:window.history.back();',1);
		exit;
	}
	/*if($size>$maxsize)                                       //超过规定大小
	{
		echo"<script>alert('上传文件大小不能超过500K! ');window.history.back();</script>";
		exit;
	}*/

	if(move_uploaded_file($tmp_name,$uploadfile))
		return $uploadfile;
	else if (copy($tmp_name,$uploadfile))
		return $uploadfile;
	else
		return false;  
}

?>
